package com.bstek.bdf4.investigate.dao;

import com.bstek.bdf.core.view.DoradoJdbcDao;
import com.bstek.bdf4.investigate.entity.Category;
import com.bstek.bdf4.investigate.entity.Investigate;
import com.bstek.dorado.data.provider.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Repository
public class InvestigateDao extends DoradoJdbcDao {
    public void getByPage(Page page, String title, String name) {

        String sql = "select id, title, author, category_id as categoryId, name, content, other,create_user as createUser, create_time as createTime, modify_user as modifyUser, modify_time as modifyTime from investigate where 1=1 ";
        List<String> params = new ArrayList();
        if (StringUtils.isNotBlank(title)) {
            sql += " and title like concat('%',?,'%')";
            params.add(title);
        }
        if (StringUtils.isNotBlank(name)) {
            sql += " and name like concat('%',?,'%')";
            params.add(name);
        }

        this.pagingQueryDorado(page, sql, params.toArray(), new BeanPropertyRowMapper<>(Investigate.class));
        Collection<Investigate> entities = page.getEntities();
        for (Investigate investigate : entities) {
            if (investigate.getCategoryId() != null) {
                Category category = this.getJdbcTemplate().queryForObject("select id, category_name from category where id = ?", new Object[]{investigate.getCategoryId()}, new BeanPropertyRowMapper<>(Category.class));
                investigate.setCategory(category);
            }
        }
    }

    public void getInvestigateByCategoryId(Page<Investigate> page, Long id) {
        JdbcTemplate jdbcTemplate = this.getJdbcTemplate();
        String sql = "select id, title, author, category_id, name, content, other,create_user, create_time, modify_user, modify_time from investigate where category_id = ?";
        this.pagingQueryDorado(page, sql, new Object[]{id}, new BeanPropertyRowMapper<>(Investigate.class));
        Collection<Investigate> investigateList = page.getEntities();
        for (Investigate investigate : investigateList) {
            if (investigate.getCategoryId() != null) {
                Category category = jdbcTemplate.queryForObject("select id, category_name from category where id = ?", new Object[]{investigate.getCategoryId()}, new BeanPropertyRowMapper<>(Category.class));
                investigate.setCategory(category);
            }
        }
    }
}
